#include <iostream>
#include <string>
#include <luaglue/luaglue.hpp>

static int read_config(lua_State *L)
{    
    if (luaL_dofile(L, "./config.txt"))
    {
        std::cout << "Failure to read config.txt: " << lua_error(L) << std::endl;
        lua_pop(L, 1);
        return -1;
    }

    luaglue::object config(L, "config");
    if (LUA_TTABLE != config.type())
    {
        std::cout << "Format error!" << std::endl;
        return -2;
    }

    auto serial_path = luaglue::object(config["serial_path"]).cast<const char *>();
    auto baudrate = luaglue::object(config["baudrate"]).cast<int>();
    auto data_bits = luaglue::object(config["data_bits"]).cast<int>();
    auto stop_bits = luaglue::object(config["stop_bits"]).cast<int>();
    auto timeout = luaglue::object(config["timeout"]).cast<double>();

    if (!(serial_path && baudrate && data_bits && stop_bits && timeout))
    {
        std::cout << "Format error!" << std::endl;
    }

    std::cout << "serial_path:\t" << *serial_path << std::endl;
    std::cout << "baudrate:\t" << *baudrate << std::endl;
    std::cout << "data_bits:\t" << *data_bits << std::endl;
    std::cout << "stop_bits:\t" << *stop_bits << std::endl;
    std::cout << "timeout:\t" << *timeout << std::endl;

    return 0;
}

int main()
{
    int ret;
    lua_State *L = luaL_newstate();

    ret = read_config(L);

    lua_close(L);

    return ret;
}

